package org.hzz.locks;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisPooled;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.Semaphore;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/developeros/videos-online">Code Repository</a>
 * At 2024/9/9
 */
@Slf4j
public class LockPubSub extends JedisPubSub {
    private final JedisPooled jedis;
    private final Semaphore latch;

    public LockPubSub(JedisPooled jedis, Semaphore latch){
        this.jedis = jedis;
        this.latch = latch;
    }

    public void publish(String channel){
        // 直接发布到key
        jedis.publish(channel,channel);
        log.debug("发布消息{}",Thread.currentThread().getId());
    }

    @Override
    public void onMessage(String channel, String message) {
        latch.release();
        log.debug("{}收到通知,释放许可",Thread.currentThread().getId());
    }

    public void subscribe(String channel){
        jedis.subscribe(this,channel);
        log.debug("订阅成功{}",Thread.currentThread().getId());
    }

    public void unsubscribe(String channel){
        super.unsubscribe(channel);
//        this.unsubscribe(channel);
        log.debug("取消订阅 {}",Thread.currentThread().getId());
    }
}
